package com.moter.demo01.juc.alllocks.optimisticlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 悲观锁
 */
public class PessimisticLock {
    Lock lock = new ReentrantLock();
    private int data=0;
    public void increment(){
        lock.lock();
        data++;
        System.out.println(Thread.currentThread().getName()+"\t"+data);
        lock.unlock();
    }

    public static void main(String[] args) {
        PessimisticLock pessimisticLock = new PessimisticLock();
        for (int i = 0; i < 20; i++) {
            new Thread(()-> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                pessimisticLock.increment();
            }).start();
        }
    }
}
